<!-- 考试分类选择页面 -->
<template>
	<view class="category-container" :style="containerStyle">
		<!-- 页面头部 -->
		<view class="header" :style="{ paddingTop: safeDistance + 'px' }">
			<view class="back-button" @click="handleGoBack">
				<text class="back-icon">←</text>
			</view>
			<view class="header-content">
				<text class="header-title">选择测试分类</text>
				<text class="header-subtitle">选择要测试的知识分类（可多选）</text>
			</view>
		</view>

		<!-- 分类列表 -->
		<scroll-view class="category-scroll" scroll-y>
			<view v-if="loading" class="loading-container">
				<text class="loading-text">加载中...</text>
			</view>

			<view v-else class="category-list">
				<view v-for="category in availableCategories" :key="category.id" class="category-card"
			:class="{ 'category-selected': selectedCategories.includes(category.code) }"
			@click="handleToggleCategory(category.code)">
			<view class="select-icon">
				<view class="icon-inner" v-if="selectedCategories.includes(category.code)"></view>
			</view>

			<view class="category-info">
				<text class="category-icon">{{ category.icon }}</text>
				<view class="category-details">
					<text class="category-name">{{ category.name }}</text>
					<text class="category-count">{{ getCategoryQuestionCount(category.code) }} 道题</text>
				</view>
			</view>

			<view v-if="selectedCategories.includes(category.code)" class="selected-badge">
				<text class="badge-text">已选</text>
			</view>
		</view>
			</view>

			<!-- 选择提示 -->
			<view class="tip-section" v-if="selectedCategories.length > 0">
				<view class="tip-card">
					<text class="tip-icon">💡</text>
					<text class="tip-text">已选择 {{ selectedCategories.length }} 个分类，将从 {{ totalSelectedQuestions }}
						道题中随机抽取 10 道进行测试</text>
				</view>
			</view>

			<view class="bottom-placeholder"></view>
		</scroll-view>

		<!-- 底部操作栏 -->
		<view class="bottom-bar">
			<button class="action-btn primary-btn" @click="handleStartTest" :disabled="selectedCategories.length === 0">
				<text class="btn-text">开始测试</text>
			</button>
		</view>
	</view>
</template>

<script setup lang="ts">
	import { onLoad } from '@dcloudio/uni-app';
	import { ref, computed } from 'vue';
	import { getCategoriesByTechCodeAPI } from '@/services/categories';
	import { getThemeStyles } from '@/stores/theme';
	import type { Category } from '@/types';

// 响应式数据
const techCode = ref(''); // 技术栈代码
const availableCategories = ref<Category[]>([]); // 可用分类列表
const selectedCategories = ref<string[]>([]); // 已选择的分类
const loading = ref(true); // 加载状态

	// 计算属性
	const themeStyles = computed(() => getThemeStyles());
	const containerStyle = computed(() => ({
		backgroundColor: themeStyles.value.bgPrimary,
		color: themeStyles.value.textPrimary
	}));
	const safeDistance = computed(() => (uni.getSystemInfoSync().safeAreaInsets?.top || 0) + 20);
	const totalSelectedQuestions = computed(() => 
		selectedCategories.value.reduce((total, categoryCode) => 
			total + getCategoryQuestionCount(categoryCode), 0
	));

// 页面加载
onLoad(async (options: any) => {
	techCode.value = options.channelCode || '';

	if (!techCode.value) {
		uni.showToast({
			title: '技术栈代码不能为空',
			icon: 'none',
			duration: 2000
		});
		setTimeout(() => uni.navigateBack(), 1500);
		return;
	}

	availableCategories.value = [];
	selectedCategories.value = [];

	try {
		loading.value = true;
		uni.showLoading({
			title: '加载中...',
			mask: true
		});

		const categoriesRes = await getCategoriesByTechCodeAPI(techCode.value);
		const categories = categoriesRes.data || [];

		if (categories.length === 0) {
			console.warn(`未找到技术Code为 "${techCode.value}" 的分类`);
		}
		availableCategories.value = categories;

		uni.hideLoading();
	} catch (error) {
		console.error('加载数据失败:', error);
		uni.hideLoading();
		uni.showToast({
				title: '加载失败，请重试',
				icon: 'none',
				duration: 2000
			});
	} finally {
		loading.value = false;
	}
});

// 工具方法
const getCategoryQuestionCount = (categoryCode: string): number => {
	const category = availableCategories.value.find(c => c.code === categoryCode);
	if (!category || !category.questionCount) return 0;
	return parseInt(category.questionCount) || 0;
};

// 事件处理
const handleToggleCategory = (categoryCode: string) => {
	const index = selectedCategories.value.indexOf(categoryCode);
	if (index > -1) {
		selectedCategories.value.splice(index, 1);
	} else {
		selectedCategories.value.push(categoryCode);
	}
};

const handleStartTest = () => {
	if (selectedCategories.value.length === 0) {
		uni.showToast({
			title: '请至少选择一个分类',
			icon: 'none',
			duration: 2000
		});
		return;
	}
	
	uni.navigateTo({
			url: `/pages/exam-records/test?channelCode=${techCode.value}&categoryCode=${selectedCategories.value.join(',')}`
		});
};

const handleGoBack = () => {
	uni.navigateBack();
};


</script>

<style lang="scss" scoped>
.category-container {
	height: 100vh;
	display: flex;
	flex-direction: column;
	overflow: hidden;
	position: relative;
	transition: background-color 0.3s ease;
}

.header {
	flex-shrink: 0;
	padding-left: 32rpx;
	padding-right: 32rpx;
	padding-bottom: 32rpx;
	background: v-bind('themeStyles.bgPrimary');
	box-shadow: v-bind('themeStyles.cardBoxShadow');
	position: relative;
	z-index: 10;
	display: flex;
	align-items: center;
	gap: 20rpx;
	box-sizing: border-box;
}

.back-button {
	width: 72rpx;
	height: 72rpx;
	background: v-bind('themeStyles.bgCard');
	border-radius: 50%;
	display: flex;
	align-items: center;
	justify-content: center;
	box-shadow: v-bind('themeStyles.cardBoxShadow');
	transition: all 0.3s ease;
	flex-shrink: 0;

	&:active {
		transform: scale(0.92);
		box-shadow: v-bind('themeStyles.hoverShadow');
	}
}

.back-icon {
	font-size: 44rpx;
	color: v-bind('themeStyles.textPrimary');
	font-weight: 700;
}

.header-content {
	flex: 1;
	display: flex;
	flex-direction: column;
	gap: 8rpx;
	padding-right: 20rpx;
}

.header-title {
	font-size: 48rpx;
	font-weight: 900;
	display: block;
	background: v-bind('themeStyles.primaryGradient');
	-webkit-background-clip: text;
	-webkit-text-fill-color: transparent;
	background-clip: text;
}

	.header-subtitle {
		font-size: 26rpx;
		color: v-bind('themeStyles.textSecondary');
		font-weight: 500;
	}

	.category-scroll {
		flex: 1;
		padding: 24rpx;
		overflow-y: auto;
		box-sizing: border-box;
		width: 100%;
	}

	.loading-container {
		display: flex;
		justify-content: center;
		align-items: center;
		padding: 100rpx 0;
	}

	.loading-text {
		font-size: 28rpx;
		color: v-bind('themeStyles.textSecondary');
	}

	.category-list {
		display: flex;
		flex-direction: column;
		gap: 16rpx;
	}

	/**
	 * 分类卡片
	 */
	/**
	 * 分类卡片样式
	 * 支持选中状态和点击效果
	 */
	.category-card {
		background: v-bind('themeStyles.bgCard');
		/* 卡片背景色 */
		border-radius: 20rpx;
		/* 圆角 */
		padding: 24rpx;
		/* 内边距 */
		display: flex;
		/* 内容横向排列 */
		align-items: center;
		gap: 20rpx;
		/* 元素间距 */
		box-shadow: v-bind('themeStyles.cardBoxShadow');
		/* 卡片阴影 */
		transition: all 0.3s ease;
		/* 平滑过渡 */
		border: 3rpx solid transparent;
		/* 透明边框，选中时显示 */
		position: relative;

		/* 点击状态 */
		&:active {
			transform: scale(0.98);
			/* 轻微缩放 */
		}
	}

	.category-selected {
		background: v-bind('themeStyles.bgSecondary');
		border-color: v-bind('themeStyles.primaryColor');
		box-shadow: v-bind('themeStyles.hoverShadow');
	}

	/**
	 * 选择图标
	 */
	.select-icon {
		width: 48rpx;
		height: 48rpx;
		border: 3rpx solid v-bind('themeStyles.borderColor');
		border-radius: 50%;
		display: flex;
		align-items: center;
		justify-content: center;
		flex-shrink: 0;
		transition: all 0.3s ease;
	}

	.category-selected .select-icon {
		border-color: v-bind('themeStyles.primaryColor');
		background: v-bind('themeStyles.bgCard');
	}

	.icon-inner {
		width: 28rpx;
		height: 28rpx;
		background: v-bind('themeStyles.primaryGradient');
		border-radius: 50%;
	}

	/**
	 * 分类信息
	 */
	.category-info {
		flex: 1;
		display: flex;
		align-items: center;
		gap: 20rpx;
	}

	.category-icon {
		font-size: 56rpx;
		line-height: 1;
	}

	.category-details {
		flex: 1;
		display: flex;
		flex-direction: column;
		gap: 8rpx;
	}

	.category-name {
		font-size: 32rpx;
		font-weight: 700;
		color: v-bind('themeStyles.textPrimary');
		line-height: 1.3;
	}

	.category-count {
		font-size: 24rpx;
		color: v-bind('themeStyles.textSecondary');
		font-weight: 600;
	}

	/**
	 * 选中标记
	 */
	.selected-badge {
		padding: 8rpx 20rpx;
		background: v-bind('themeStyles.primaryGradient');
		border-radius: 100rpx;
		box-shadow: v-bind('themeStyles.buttonBoxShadow');
	}

	.badge-text {
		font-size: 24rpx;
		font-weight: 700;
		color: white;
	}

	/**
	 * 提示区域
	 */
	.tip-section {
		margin-top: 32rpx;
		margin-bottom: 16rpx;
	}

	.tip-card {
		background: v-bind('themeStyles.warningGradient');
		border-radius: 16rpx;
		padding: 20rpx 24rpx;
		display: flex;
		align-items: center;
		gap: 12rpx;
		border: 2rpx solid v-bind('themeStyles.warningColor');
	}

	.tip-icon {
		font-size: 32rpx;
	}

	.tip-text {
		font-size: 26rpx;
		color: v-bind('themeStyles.warningColor');
		font-weight: 600;
		line-height: 1.5;
	}

	/**
	 * 底部占位
	 */
	.bottom-placeholder {
		height: 120rpx;
	}

	/**
	 * 底部操作栏
	 */
	/**
	 * 底部操作栏样式
	 * 固定在底部，考虑安全区域
	 */
	.bottom-bar {
		flex-shrink: 0;
		/* 固定高度 */
		padding: 24rpx 32rpx;
		padding-bottom: calc(24rpx + env(safe-area-inset-bottom));
		/* 考虑底部安全区域 */
		background: v-bind('themeStyles.bgCard');
		/* 卡片背景色 */
		box-shadow: v-bind('themeStyles.cardBoxShadow');
		/* 顶部阴影 */
		position: relative;
		z-index: 10;
		/* 确保在内容之上 */
	}

	/**
	 * 操作按钮样式
	 * 渐变背景，点击有缩放效果，禁用状态有特殊样式
	 */
	.action-btn {
		width: 100%;
		/* 占满容器宽度 */
		height: 96rpx;
		/* 固定高度 */
		border-radius: 16rpx;
		/* 圆角 */
		display: flex;
		/* 内容居中 */
		align-items: center;
		justify-content: center;
		border: none;
		/* 无边框 */
		background: v-bind('themeStyles.primaryGradient');
		/* 渐变背景 */
		box-shadow: v-bind('themeStyles.buttonBoxShadow');
		/* 按钮阴影 */
		transition: all 0.3s ease;
		/* 平滑过渡 */

		/* 点击激活状态 */
		&:active {
			transform: scale(0.97);
			/* 轻微缩放 */
		}

		/* 禁用状态 */
		&[disabled] {
			opacity: 0.5;
			/* 半透明 */
			box-shadow: none;
			/* 移除阴影 */
		}
	}

	.btn-text {
		font-size: 32rpx;
		font-weight: 700;
		color: white;
	}
</style>